import 'package:mahjong/const/MahjongConst.dart';
import 'package:mahjong/entity/MessageContext.dart';
import 'package:mahjong/entity/UserTask.dart';
import 'package:mahjong/entity/UserTouchBar.dart';
import 'package:mahjong/entity/card/MahjongCardEntity.dart';
import 'package:mahjong/entity/mahjong/LicensingCard.dart';
import 'package:mahjong/entity/user/MahjongUserInfo.dart';
import 'package:mahjong/entity/card/MahjongUserSwapCard.dart';
import 'package:mahjong/util/AudioPlayUtil.dart';
import 'package:mahjong/util/MessageUtils.dart';

class MahjongUserNotify extends MahjongUserInfo {
  List<MahjongCardEntity> userCards;
  List<MahjongCardEntity> userExportCards;
  int cardCount;
  // 当前用户的任务
  UserTask userTask;
  // 是不是当前用户出的牌
  bool pervExportUser;
  // 用户的碰牌信息
  List<UserTouchBar> userTouchBar;
  String userDoAction;
  bool showDoAction = false;

  void showAction(String action) {
    if (!["CARD_BAR", "CARD_CALL", "CARD_HU", "CARD_TOUCH"].contains(action)) {
      return;
    }
    this.userDoAction = action;
    this.showDoAction = true;
    updateView();
    Future.delayed(Duration(seconds: 2), () {
      this.showDoAction = false;
      updateView();
    });
  }

  void cleanUserInfo() {
    this.userId = null;
    this.banker = null;
    this.seq = null;
    this.online = null;
    this.win = null;
    this.integral = null;
    this.prepare = null;
    this.gameType = null;
    this.huCard = null;
    this.swap = null;
    this.sysUser = null;
    this.listening = null;
    this.winCount = null;
    this.callHuCards = null;
  }

  void updateHighlight(int cardId) {
    diskPartUserProvider.forEach((key, value) {
      if (value.userExportCards == null || value.userExportCards.length == 0) {
        return;
      }
      value.userExportCards.forEach((item) {
        if (item.cardId == cardId && cardId != null) {
          item.highlight = true;
        } else {
          item.highlight = false;
        }
      });

      if (value.userTouchBar == null || value.userTouchBar.length == 0) {
        return;
      }
      value.userTouchBar.forEach((item) {
        if (item.cards == null || item.cards.length == 0) {
          return;
        }
        item.cards.forEach((uitem) {
          if (uitem.cardId == cardId && cardId != null) {
            uitem.highlight = true;
          } else {
            uitem.highlight = false;
          }
        });
      });
      value.updateView();
    });
  }

  void updateTask(data) {
    if (null != data) {
      this.userTask = UserTask.fromJson(data);
    }
    notifyListeners();
  }

  /**
    * 判断是否有某个Task任务
    */
  bool hasTask(String taskParam) {
    bool result = false;
    if (null == this.userTask) {
      return false;
    }
    var taskArray = this.userTask.taskArray;
    if (this.userTask.task != null && this.userTask.task == taskParam) {
      return true;
    }
    if (taskArray != null && taskArray.length > 0) {
      for (int i = 0, j = taskArray.length; i < j; i++) {
        if (taskArray[i] == taskParam) {
          result = true;
          break;
        }
      }
    }
    return result;
  }

  MahjongUserNotify(this.userCards) {
    this.userExportCards = [];
  }
  // 添加手牌
  void addCard(int cardId) {
    this.userCards.add(MahjongCardEntity(cardId: cardId, isClick: true));
    notifyListeners();
  }

  List<MahjongCardEntity> cardsToMahjongEntity(List<dynamic> cards,
      {bool isClick = true}) {
    List<MahjongCardEntity> result = [];
    if (cards != null) {
      cards.forEach((cardId) {
        result.add(MahjongCardEntity(
            cardId: int.parse(cardId.toString()), isClick: isClick));
      });
    }

    return result;
  }

  // 交换完毕
  void swapAfter() {
    this.userCards.forEach((item) {
      item.isClick = true;
    });

    this.userCards.sort((a, b) {
      return a.cardId - b.cardId;
    });
    notifyListeners();
  }

  // 交换完毕
  void swapSuccess(MahjongUserSwapCard userSwapCard, int size) {
    this.swap = false;
    if (userSwapCard != null && userSwapCard.inSwapCard.cards != null) {
      this.userSwapCard = userSwapCard;
      this.userCards.addAll(
          cardsToMahjongEntity(userSwapCard.inSwapCard.cards, isClick: false));
    }
    if (null != size) {
      this.cardCount = size;
    }
    notifyListeners();
  }

  currentExport(currentExport) {}

  void otherExport(cardId) {
    this.cardCount--;
    this.pervExportUser = true;
    this.userExportCards.add(MahjongCardEntity(cardId: cardId));
    notifyListeners();
  }

  void updateView() {
    notifyListeners();
  }

  void cleanTask() {
    this.userTask = null;
    notifyListeners();
  }

  void exchangeCard(List<int> selectArray) {
    selectArray.sort((a, b) {
      return a - b;
    });
    for (int i = selectArray.length - 1; i >= 0; i--) {
      this.userCards.removeAt(selectArray[i]);
    }
    this.swap = true;
    cleanTask();
  }

  void offLine() {
    this.online = false;
    notifyListeners();
  }

  void connectOnLine() {
    this.online = true;
    notifyListeners();
  }

  void cardCall() {
    this.listening = true;
    notifyListeners();
  }

  /**
   * 玩家摸牌操作
   */

  void otherLicensing() {
    this.cardCount += 1;
    notifyListeners();
  }

  /**
   * 玩家状态刷新
   */
  void updateUserState(MahjongUserInfo userInfo) {
    updateUser(userInfo);
    notifyListeners();
  }

  // 当前玩家进行摸牌操作

  void currentLicensing(LicensingCard licensingCard) {
    this.userCards.add(
        MahjongCardEntity(cardId: licensingCard.licensingCard, isClick: true));
    notifyListeners();
    // 当用户报叫过后 自动出牌
    if (this.listening &&
        !checkUserTask(licensingCard.userTask, [MessageAction.CARD_HU]) &&
        !checkUserTask(licensingCard.userTask, [MessageAction.CARD_BAR])) {
      Future.delayed(Duration(milliseconds: 500), () {
        if (MessageUtils.sendMessage(new MessageContext(
                action: MessageAction.EXPORT_CARD,
                body: licensingCard.licensingCard)
            .toString())) {
          AudioPlayUtil.playExportCard(licensingCard.licensingCard);
          exportCard(licensingCard.licensingCard);
          diskPartUserProvider.forEach((key, value) {
            if (key != this.userId) {
              value.pervExportUser = false;
              value.updateView();
            }
          });
        }
      });
    }
  }
  /* 
   * 判断用户是否有这个行为
   */

  bool checkUserTask(UserTask task, List<String> action) {
    var result = true;
    if (task == null) {
      return false;
    } else if (task.task != null && action.contains(task.task)) {
      return true;
    } else if (task.taskArray != null && task.taskArray.length > 0) {
      action.forEach((element) {
        if (!task.taskArray.contains(element) && result) {
          result = false;
        }
      });
    }
    return result;
  }

  void initOtherUser(
      dynamic data, MahjongUserInfo userInfo, String exportUserId) {
    updateUser(userInfo);
    initUserTouchBar(data["userTouchBar"], this.userId);
    if (exportUserId != null && this.userId == exportUserId) {
      this.pervExportUser = true;
    } else {
      this.pervExportUser = false;
    }
    this.userExportCards = [];
    var userExportResult = data["userExportCards"];
    var otherUserMap = data["otherUserInfo"];
    if (null != userExportResult) {
      this.userExportCards = caseToList(userExportResult[this.userId]);
    }
    if (otherUserMap != null) {
      var otherMap = Map.castFrom(otherUserMap);
      otherMap.forEach((key, value) {
        if (key == this.userId) {
          cardCount = value["userCardLength"];
        }
      });
    }
    notifyListeners();
  }

  void initCurrentInfo(dynamic data, String exportUserId) {
    updateUser(MahjongUserInfo.fromJson(data["currentUserInfo"]));
    if (exportUserId != null && this.userId == exportUserId) {
      this.pervExportUser = true;
    } else {
      this.pervExportUser = false;
    }
    this.userCards = cardsToMahjongEntity(data["currentUserCards"]);
    this.userTask = UserTask.fromJson(data["currentUserTask"]);
    this.userExportCards = [];
    var userExportCards = data["userExportCards"];
    initUserTouchBar(data["userTouchBar"], this.userId);
    if (null != userExportCards) {
      this.userExportCards = caseToList(userExportCards[this.userId]);
    }
    notifyListeners();
  }

  void initUserTouchBar(data, String userId) {
    this.userTouchBar = [];

    if (data != null) {
      Map.castFrom(data).forEach((key, value) {
        if (key == userId && value != null) {
          var result = List.castFrom(value);
          result.forEach((element) {
            this.userTouchBar.add(UserTouchBar.fromJson(element));
          });
        }
      });
    }
  }

  List<MahjongCardEntity> caseToList(List<dynamic> data) {
    if (data == null) {
      return [];
    }
    List<MahjongCardEntity> result = [];
    data.forEach((element) {
      var code = int.parse(element.toString());
      result.add(MahjongCardEntity(cardId: code));
    });
    return result;
  }

  void exportCard(int cardId) {
    this.userExportCards.add(MahjongCardEntity(cardId: cardId));
    this.userTask = null;
    this.pervExportUser = true;
    for (int i = this.userCards.length - 1; i >= 0; i--) {
      if (cardId == this.userCards[i].cardId) {
        this.userCards.removeAt(i);
        break;
      }
    }
    this.userCards.sort((a, b) {
      return a.cardId - b.cardId;
    });
    notifyListeners();
  }

  void addUserCardCount() {
    userCards.add(new MahjongCardEntity());
  }

  void updatePrepare() {
    this.prepare = true;
    notifyListeners();
  }

  Map<String, dynamic> toJson() => <String, dynamic>{
        'userId': userId,
        'banker': banker,
        'huCard': huCard,
        'seq': seq,
        'win': win,
        'online': online,
        'integral': integral,
        'prepare': prepare,
        'gameType': gameType,
      };
}
